package com.wangbo.countDownLatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 任务分解
 */
public class Client {

    public static void main(String[] args) throws InterruptedException {
        // 创建计数器
        CountDownLatch countDownLatch = new CountDownLatch(2);

        // 创建固定线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(2);

        // 任务1
        Runnable task1 = () -> {
            try {
                // 模拟工作
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("我是任务1");
            countDownLatch.countDown();
        };

        // 任务2
        Runnable task2 = () -> {
            try {
                // 模拟工作
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("我是任务2");
            countDownLatch.countDown();
        };

        // 执行任务
        threadPool.submit(task1);
        threadPool.submit(task2);
        threadPool.shutdown();

        // 主线程阻塞，等待任务执行完毕
        countDownLatch.await();
        System.out.println("我是主线程，任务结束，我来收尾");

        // 主线程阻塞指定时间，过时不候
//        countDownLatch.await(2, TimeUnit.SECONDS);
//        System.out.println("我是主线程，我等不及了,先走啦");

    }
}
